package com.ccp.dev.qbdms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.util.PropertyUtil;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.extend.service.ExtendSysOrgService;
import com.ccp.dev.qbdms.consts.ZhiLiangConst;
import com.ccp.dev.qbdms.enums.FlowStatusEnum;
import com.ccp.dev.qbdms.expimp.util.AbstractExpUtil;
import com.ccp.dev.qbdms.expimp.util.AuxiliaryUtil;
import com.ccp.dev.qbdms.model.WQbdQcAchievement;
import com.ccp.dev.qbdms.model.WQbdQcGroup;
import com.ccp.dev.qbdms.service.WQbdFalSuperviseService;
import com.ccp.dev.qbdms.service.WQbdQcAchievementService;
import com.ccp.dev.qbdms.util.BaseUtil;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.qbdms.util.StructureModifyUtil;
import com.ccp.dev.system.model.Dictionary;
import com.ccp.dev.system.model.SysOrg;
import com.ccp.dev.system.model.SysRole;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.workflow.model.ProcessRun;
import com.ccp.dev.workflow.model.TaskOpinion;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;
import com.ccp.dev.workflow.service.TaskOpinionService;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * QC成果 信息操作处理控制器
 *
 * @author 王明亮
 * @date 2020-06-22 14:31:38
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "QC成果")
@RequestMapping("/qbdms/wQbdQcAchievement")
public class WQbdQcAchievementController extends SysBaseController {
    @Resource
    private WQbdQcAchievementService wQbdQcAchievementService;
    @Resource
    private ExtendSysOrgService extendSysOrgService;
    @Resource
    private WQbdFalSuperviseService wQbdFalSuperviseService;
    @Resource
    private ProcessRunService processRunService;
    @Resource
    private TaskOpinionService taskOpinionService;

    /**
     * 功能描述: 跳转到首页
     *
     * @param modelMap
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "跳转到QC成果首页", exectype = "页面跳转日志")
    public String viewList(HttpServletRequest request, ModelMap modelMap) {
        // 当前组织
        SysOrg currentOrg = (SysOrg) ContextUtil.getCurrentOrg();
        // 当前系统等级
        BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
        modelMap.put("currentSystemLevel", currentSystemLevel);

        SysRole sysRole = (SysRole) request.getSession().getAttribute(SysRole.CURRENT_SYSROLE);
        if (sysRole.getAlias().equals("bpm_zlzhzly") || sysRole.getAlias().equals("bpm_qnzl")) {
            modelMap.put("canEdit", "true");
        } else {
            modelMap.put("canEdit", "false");
        }
        modelMap.put("rolealis", sysRole.getAlias());
        // 注册单位
        List<Dictionary> registrationUnitList = new ArrayList<>();
        if (BaseUtil.SystemLevel.GROUPLEVEL.equals(currentSystemLevel)) {
            // 集团公司下拉框内容为二级、三级单位名称
            HashMap<Object, Object> paramMap = new HashMap<>(16);
            paramMap.put("current", "0");
            List<Map> org2 = wQbdFalSuperviseService.getOrg2(paramMap);
            List<Dictionary> finalRegistrationUnitList = registrationUnitList;
            org2.forEach(map -> {
                Dictionary dictionary = new Dictionary();
                dictionary.setItemName(String.valueOf(map.get("ORGNAME")));
                dictionary.setItemValue(String.valueOf(map.get("CODE")));
                finalRegistrationUnitList.add(dictionary);
            });
        } else if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
            // 二级单位下拉框的内容为三级单位名称
            List<Dictionary> originOrgToDicList = extendSysOrgService.getSubordinateUnits();
            if (originOrgToDicList.stream().noneMatch(dictionary -> currentOrg.getCode().equals(dictionary.getItemValue()))) {
                Dictionary dictionary = new Dictionary();
                dictionary.setItemName(currentOrg.getOrgName());
                dictionary.setItemValue(currentOrg.getCode());
                originOrgToDicList.add(dictionary);
            }
            registrationUnitList = originOrgToDicList;
        }
        modelMap.put("registrationUnitList", JSON.toJSONString(registrationUnitList));
        modelMap.put("currentUserId", ContextUtil.getCurrentUserId());
        return "wQbdQcAchievement/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description = "附带检索条件的分页查询QC成果", detail = "查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) throws IllegalAccessException {
        QueryFilter queryFilter = new QueryFilter(request, true);
        // 默认按照评定时间倒序排列,评定时间相同的情况下按创建时间倒序排列
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "evaluation_time");
            queryFilter.addFilter("orderSeq", "desc");
            queryFilter.addFilter("orderField1", "createtime");
            queryFilter.addFilter("orderSeq1", "desc");
        }
        ZhiLiangConst.addQueryFilter(queryFilter);

        //分页数据
        List<WQbdQcAchievement> pageDatas = wQbdQcAchievementService.queryList(queryFilter);
        // 密级、上报状态、数据来源单位显示中文
        ZhiLiangConst.showName(pageDatas);
        //判断流程状态
        ZhiLiangConst.isDataAllowEditByFlowStatus(pageDatas);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "跳转到QC成果新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request, ModelMap modelMap) {
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
            runId=processRun.getRunId();
            List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
            for(TaskOpinion taskOpinion:taskOpinionList){
                if(taskOpinion.getEndTime()!=null){
                    taskOpinionNewList.add(taskOpinion);
                }
            }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        if (StringUtils.isNotBlank(id)) {
            WQbdQcAchievement wQbdQcAchievement = wQbdQcAchievementService.getOneById(id);
            modelMap.put("flowStatus", wQbdQcAchievement.getFlowStatus());
        }
        return "wQbdQcAchievement/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdQcAchievement 保存的对象
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description = "保存QC成果数据", detail = "<#if isAdd>新增<#else>编辑</#if>QC成果数据<#if success>成功<#else>失败</#if><#if StringUtil.isNotEmpty(modifyInfo)>${modifyInfo}</#if>")
    public Object save(@RequestBody WQbdQcAchievement wQbdQcAchievement) {
        String id = wQbdQcAchievement.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd", true);
            //新增操作
            //新增数据前生成随机Id
            wQbdQcAchievement.setId(ProjectUUIDUtils.getUUIDFor32());
            ZhiLiangConst.addCommonFields(wQbdQcAchievement);
            //上报状态
            BaseUtil.SystemLevel currentSystemLevel = BaseUtil.getCurrentSystemLevel();
            if (BaseUtil.SystemLevel.HOSPITALLEVEL.equals(currentSystemLevel)) {
                wQbdQcAchievement.setReportStatus(ZhiLiangConst.REPORT_STATUS_GROUPTOBEREPORTED);
            } else if (BaseUtil.SystemLevel.PLANTLEVEL.equals(currentSystemLevel)) {
                wQbdQcAchievement.setReportStatus(ZhiLiangConst.getDataInitStatusToHospital());
            }
            wQbdQcAchievement.setFlowStatus(FlowStatusEnum.NOT_SUBMIT.getValue());
            result = wQbdQcAchievementService.add(wQbdQcAchievement);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            //修改操作
            ZhiLiangConst.updateCommonFields(wQbdQcAchievement);
            result = wQbdQcAchievementService.update(wQbdQcAchievement);
            SysAuditThreadLocalHolder.putParamerter("modifyInfo", StructureModifyUtil.getModifyInfo(wQbdQcAchievementService.getOneById(id), wQbdQcAchievement));
        }
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        Map<String,Object> idMap= Maps.newHashMap();
        idMap.put("id",wQbdQcAchievement.getId());
        return result > 0 ? getResultDataSuccess("save.success",idMap) : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description = "跳转到QC成果详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request, ModelMap modelMap) {
        String flag = RequestUtil.getString(request, "flag");
        modelMap.put("flag", flag);
        String id = RequestUtil.getString(request, "id");
        modelMap.put("id", id);
        String isClose = RequestUtil.getString(request, "isClose");
        modelMap.put("isClose", isClose);
        String runId="";
        List<TaskOpinion> taskOpinionNewList = new ArrayList<TaskOpinion>();
        ProcessRun processRun=processRunService.getByBusinessKey(id);
        if(BeanUtils.isNotEmpty(processRun)){
          runId=processRun.getRunId();
          List<TaskOpinion> taskOpinionList = taskOpinionService.getByRunId(runId);
          for(TaskOpinion taskOpinion:taskOpinionList){
            if(taskOpinion.getEndTime()!=null){
              taskOpinionNewList.add(taskOpinion);
            }
          }
        }
        modelMap.put("taskOpinionNewList", taskOpinionNewList);
        WQbdQcAchievement wQbdQcAchievement = wQbdQcAchievementService.getOneById(id);
        modelMap.put("flowStatus", wQbdQcAchievement.getFlowStatus());
        modelMap.put("runId", runId);
        modelMap.put("processRun", processRun);
        return "wQbdQcAchievement/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description = "根据主键id查询QC成果的一条数据", detail = "根据主键id查询QC成果的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdQcAchievement wQbdQcAchievement = wQbdQcAchievementService.getOneById(id);
        if (null == wQbdQcAchievement) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return getResultDataError("get.failure");
        }
        FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdQcAchievement.getFlowStatus());
        wQbdQcAchievement.setFlowStatusStr(flowStatusEnum.getName());
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("get.success", wQbdQcAchievement);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "根据主键ID删除QC成果数据", exectype = "删除日志", detail = "删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) throws Exception{
        String userId = ContextUtil.getCurrentUserId();
        String[] ids = id.split(",");
        for (String key : ids) {
            WQbdQcAchievement wQbdQcAchievement = wQbdQcAchievementService.getOneById(key);

            //判断流程状态
            FlowStatusEnum flowStatusEnum = FlowStatusEnum.getEnumByValue(wQbdQcAchievement.getFlowStatus());
            if (!flowStatusEnum.isDel()) {
                SysAuditThreadLocalHolder.putParamerter("success", false);
                return fail("删除失败，不允许删除流程未结束数据！");
            }
            if (!userId.equals(wQbdQcAchievement.getCreateBy())) {
                return fail("删除失败！只能删除自己创建的数据！");
            }
        }
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            return fail("delete.failure.message");
        }
        //流程实例删除
        for (String key : ids) {
            WQbdQcAchievement wQbdQcAchievement = wQbdQcAchievementService.getOneById(key);
            if(!wQbdQcAchievement.getFlowStatus().equals(FlowStatusEnum.NOT_SUBMIT.getValue()) && StringUtil.isNotEmpty(wQbdQcAchievement.getFlowStatus())){
                ProcessRun processRun = processRunService.getByBusinessKey(key);
                if(processRun!=null){
                    processRunService.deleteByProcessRun(processRun);
                }
            }
        }
        int result = wQbdQcAchievementService.delByIdArray(id.split(","));
        if (result > 0) {
            SysAuditThreadLocalHolder.putParamerter("success", true);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success", false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description = "跳转到QC成果导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdQcAchievement/import";
    }

    /**
     * 功能描述: 跳转到导出选择字段页面
     *
     * @param request
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/export")
    @Action(description = "跳转到QC成果导出选择字段页面", exectype = "页面跳转日志")
    public String export(HttpServletRequest request, ModelMap modelMap) throws Exception {
        com.alibaba.fastjson.JSONObject jsonObject = AuxiliaryUtil.resolverModel(WQbdQcAchievement.class);
        modelMap.put("tableInfo", jsonObject.toString());
        return "expImp/add";
    }

    /**
     * 功能描述: 导出QC成果数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: 王明亮
     * @date: 2020-06-22 14:31:38
     */
    @RequestMapping("/exportData")
    @Action(description = "导出QC成果数据信息", detail = "导出QC成果数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysAuditThreadLocalHolder.putParamerter("success", false);
        String[] id = RequestUtil.getStringAryByStr(request, "id");
        QueryFilter queryFilter = new QueryFilter(request, false);
        JSONArray dataArray = ZhiLiangConst.exportAddConditions(queryFilter, id);
        if (StringUtil.isEmpty(queryFilter.get("orderField"))) {
            queryFilter.addFilter("orderField", "evaluation_time");
            queryFilter.addFilter("orderSeq", "desc");
            queryFilter.addFilter("orderField1", "createtime");
            queryFilter.addFilter("orderSeq1", "desc");
        }
        List<WQbdQcAchievement> wQbdQcAchievements = this.wQbdQcAchievementService.queryAll(queryFilter);
        if (wQbdQcAchievements.isEmpty()) {
            wQbdQcAchievements.add(new WQbdQcAchievement());
        }
        new AbstractExpUtil() {
            @Override
            public String customAnalysis(String fieldName, String fieldValue) {
                return null;
            }
        }.executeExport(request, response, wQbdQcAchievements, dataArray, AbstractExpUtil.ExpStyle.MANY_SHEET);
        SysAuditThreadLocalHolder.putParamerter("success", true);
    }

    /**
     * 导入资源文件
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdQcAchievement> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdQcAchievement dataToInsert = new WQbdQcAchievement();
                int i = 0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                    //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(UUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdQcAchievementService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success", true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success", false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        }
    }

    /**
     * 查询上报的信息
     *
     * @param id        业务数据主键
     * @param tableName 业务表名
     * @return
     */
    @RequestMapping("/reportList")
    @ResponseBody
    public Object reportList(@RequestParam("id") String id, @RequestParam("tableName") String tableName) throws IllegalAccessException {
        //业务数据
        List<WQbdQcAchievement> reportList = wQbdQcAchievementService.reportList(id, tableName);
        ZhiLiangConst.showName(reportList);
        SysAuditThreadLocalHolder.putParamerter("success", true);
        return getResultDataSuccess("options.success", reportList);
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动QC成果流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdQcAchievement wQbdQcAchievement){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdQcAchievement.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("QCcgwsplc");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(isList == 1){
                wQbdQcAchievement = wQbdQcAchievementService.getOneById(id);
            }
            processCmd.setBusinessKey(id);
            processRunService.startProcess(processCmd);
            wQbdQcAchievement.setFlowStatus(FlowStatusEnum.APPROVAL_ING2.getValue());
            wQbdQcAchievementService.update(wQbdQcAchievement);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }
}
